<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <el-dialog v-model="props.preViewVisible" title="预览" @close="handleVisible('cancel')">
    <div class="bdf_name">
      <span>文件名称：</span>
      <span>{{ props.data.fileName }}</span>
    </div>
    <div class="bdf" v-loading="loading">
      <div class="bdf_search" v-if="searchVisible">
        <el-input size="small" v-model.trim="searchContent" style="width: 140px" placeholder="请输入要查询的内容" />
        <el-button type="primary" size="small" style="margin-left: 10px" @click="searchFn">搜索</el-button>
        <el-button size="small" icon="Top" @click="preFn">上一个</el-button>
        <el-button size="small" icon="Bottom" @click="nextFn">下一个</el-button>
        <el-button size="small" icon="Close" @click="closeSearch">关闭</el-button>
      </div>
      <div style="width: 100%; max-height: 300px; overflow: auto" id="preViewContent" class="bdf_info"></div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" type="primary" @click="handleVisible('submit')">关闭</el-button>
      </div>
    </template>
    <div id="bdfTmp" style="display: none"></div>
  </el-dialog>
</template>
<script name="bdfPreView" setup>
import { queryBdfFileInfo } from '@/api/elementsLibrary';
const props = defineProps(['preViewVisible', 'data']);
const emits = defineEmits(['handleEvent']);
const loading = ref(false);
const searchVisible = ref(false);
const searchContent = ref();
//当前文本搜索的所有内容
const elements = ref([]);
// 搜索内容当前显示的位置索引
const currentSearchIndex = ref(0);

const handleVisible = (type) => {
  emits('handleEvent', { type: 'preView' });
};
// 查询BDF文件
const getFileInfo = () => {
  const params = {
    classification: props.data.classification,
    uri: props.data.uri
  };
  queryBdfFileInfo(params)
    .then((res) => {
      if (res) {
        const bdfDom = document.getElementById('preViewContent');
        const dom = document.getElementById('bdfTmp');
        if (dom) {
          dom.innerText = res;
          const splitArray = dom.innerHTML.split('<br>') || [];
          //CQUAD4开始下标
          let startIndex = splitArray.findIndex((item) => item.startsWith('CQUAD4'));
          //CQUAD4结束下标
          let endIndex = -1;
          for (let i = splitArray.length; i >= 0; i--) {
            const item = splitArray[i] || '';
            if (item.startsWith('CQUAD4')) {
              endIndex = i;
              break;
            }
          }
          console.log(startIndex)
          console.log(endIndex)
          // //将text内容转为html格式
          for (let i = 0; i < startIndex; i++) {
            splitArray[i] = `<div style="white-space:pre;">${splitArray[i]}</div>`;
          }
          for (let i = endIndex + 1; i < splitArray.length; i++) {
            splitArray[i] = `<div style="white-space:pre;">${splitArray[i]}</div>`;
          }
          for (let i = startIndex; i <= endIndex; i++) {
            splitArray[i] = setItemColor(splitArray[i]);
          }
          const bdfHtml = splitArray.join('');
          //dom展示
          bdfDom.innerHTML = bdfHtml;
        }
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
// 设置CQUAD4单元颜色
const setItemColor = (CQUAD4) => {
  if(!CQUAD4){
    return;
  }
  let data = CQUAD4.split('  ');
  const colorArr = data.slice(1, data.length);
  const colorStr = colorArr.join('  ');
  const step = 8;
  const num = colorStr.length / step;
  let str = '';
  for (let i = 0; i < num; i++) {
    const color1 = '#d7d7d7';
    const color2 = '#f2f2f2';
    let color = '';
    let strItem = colorStr.slice(i * 8, (i + 1) * 8);
    //交替设置颜色
    if (i % 2 === 0) {
      color = color1;
    } else {
      color = color2;
    }
    str += `<span style="white-space:pre;width:54px;display: inline-block;background: ${color};">${strItem}</span>`;
  }
  const showStr = `<div style="white-space:pre;">${data[0]}&nbsp;&nbsp;${str}</div>`;
  return showStr;
};
const closeSearch = () => {
  searchVisible.value = false;
};
const searchFn = () => {
  if (searchContent.value) {
    findText();
  }
};
// 下一个
const nextFn = () => {
  currentSearchIndex.value++;
  scrollToContent(currentSearchIndex.value);
};
// 上一个
const preFn = () => {
  currentSearchIndex.value--;
  scrollToContent(currentSearchIndex.value);
};
// 查找
const findText = async () => {
  const bdfDomHtml = document.getElementById('preViewContent').innerHTML;
  //先置空之前设置的样式
  const resetHtml1 = bdfDomHtml.replaceAll(`<span class="search_span" style="background:#bbd6fb;">`, ``);
  const resetHtml2 = resetHtml1.replaceAll(`</span>`, ``);
  const repalceStr = resetHtml2.replaceAll(searchContent.value, `<span class="search_span" style="background:#bbd6fb;">${searchContent.value}</span>`);
  document.getElementById('preViewContent').innerHTML = repalceStr;
  // 查找所有匹配selector的元素
  elements.value = document.querySelectorAll(`.search_span`) || [];
  if (elements.value.length === 0) {
    ElMessage({ showClose: true, message: '未检索到相关查询内容', type: 'waring' });
    return;
  }
  scrollToContent(0);
};
const scrollToContent = (index) => {
  // 默认滚动至第一条数据位置
  if (elements.value.length > 0) {
    if (elements.value[index]) {
      elements.value[index].scrollIntoView({ behavior: 'smooth' });
    }
  } else {
    ElMessage({ showClose: true, message: '未检索到相关查询内容', type: 'waring' });
  }
};
onMounted(() => {
  getFileInfo();
  window.addEventListener('keydown', function (e) {
    if (e.ctrlKey && e.key === 'f') {
      e.preventDefault();
      searchVisible.value = true;
    }
  });
});
onUnmounted(() => {
  window.removeEventListener('keydown', function () {});
});
</script>
<style lang="scss" scoped>
.bdf_name {
  > span:nth-child(1) {
    font-weight: 600;
  }
}
.bdf {
  position: relative;
  width: 100%;
  max-height: 300px;
  display: flex;
  flex-direction: column;
  // align-items: end;
  .bdf_search {
    // width: 500px;
    position: sticky;
    top: 0;
    display: flex;

    border: 1px solid #e8e8e8;
    padding: 5px 10px;
    // border-radius: 10px;
    background: #fff;
  }
}
.bdf_info {
  margin-top: 10px;
  border: 1px solid #dddddd7a;
  padding: 10px;
}
</style>
